/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rie06.openvoip.sound;

import com.rie06.openvoip.client.Conversation;
import java.io.ByteArrayOutputStream;
import java.util.*;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 *
 * @author clement
 */
public class AudioPlayer extends AudioSpecification implements Runnable {

    private static final Logger logger = Logger.getLogger(AudioPlayer.class);
    private Thread thread;

    public AudioPlayer() {
        super();
        setPause(true);

        if (initListeningLine()) {
            thread = new Thread(this);
            thread.setName("Lecture");
            thread.start();
        }
    }

    public void stopConversation() {
        thread = null;
    }

    public Thread getThread() {
        return thread;
    }

    public Queue<byte[]> getSound() {
        Queue<byte[]> q = new LinkedList<byte[]>();
        logger.log(Level.ERROR, "Need to implements getSound");
        return q;
    }

    private void verifyPause() {
        try{
        synchronized (thread) {
            while (isPause()) {
                logger.log(Level.DEBUG, "Set player pause.");
                try {
                    thread.wait();
                    logger.log(Level.DEBUG, "Set player start.");
                } catch (Exception e) {
                }
            }
        }
        }catch(NullPointerException ex){
            logger.log(Level.DEBUG, "User quit -> Exit pause.");
        }
    }

    @Override
    public void run() {

        //Micka Code

//        socketUDP.receive(donneesRecues);
//        line.write(donneesRecues.getData(), 0, donneesRecues.getLength());

        System.out.println("Start: Thread(Lecture.java)");

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int frameSizeInBytes = getFormat().getFrameSize();
        byte[] buffer = new byte[getBufSize()];

        getListeningLine().start();

        int i = 0;

        while (thread != null) {

            verifyPause();

            while (getSound().isEmpty() && thread != null) {
                verifyPause();
            }

            while (!getSound().isEmpty()) {
                buffer = getSound().poll();
                if (buffer != null) {
                    getListeningLine().write(buffer, 0, buffer.length);
                    i++;
                }
            }

        }
    }
}
